package vip.zhenzicheng.nettyadv;

import vip.zhenzicheng.nettyadv.vo.User;
import vip.zhenzicheng.nettyadv.vo.UserContact;

import java.util.Scanner;

/**
 * 业务方调用Netty示例
 *
 * @author zhenzicheng
 * @date 2022-06-14 10:26
 */
public class BusyClient {

  public static void main(String[] args) throws Exception {
    NettyClient nettyClient = new NettyClient();
    new Thread(nettyClient).start();

    while (!nettyClient.isConnected()) {
      synchronized (nettyClient) {
        nettyClient.wait();
      }
    }
    System.out.println("网络通信已准备好，可以进行业务操作了........");
    Scanner scanner = new Scanner(System.in);
    while (true) {
      String msg = scanner.next();
      if (msg == null) {
        break;
      } else if ("q".equalsIgnoreCase(msg)) {
        nettyClient.close();
        scanner.close();
        while (nettyClient.isConnected()) {
          synchronized (nettyClient) {
            System.out.println("等待网络关闭完成....");
            nettyClient.wait();
          }
        }
        System.exit(1);
      } else if ("v".equalsIgnoreCase(msg)) {
        User user = new User();
        user.setAge(19);
        String userName = "mark";
        user.setUserName(userName);
        user.setId("No:1");
        user.setUserContact(new UserContact(userName + "@qq.com", "133"));
        nettyClient.send(user);
      } else if ("o".equalsIgnoreCase(msg)) {
        User user = new User();
        user.setAge(23);
        String userName = "oneway";
        user.setUserName(userName);
        user.setId("No:1");
        user.setUserContact(new UserContact(userName + "@qq.com", "331"));
        nettyClient.sendOneWay(user);
      } else {
        nettyClient.send(msg);
      }
    }
  }
}
